package Thread;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

/**
 * @author 杜伟毅
 * @version 1.0
 * @since 2024/08/03
 * 多线程（有返回值）
 */
public class UseCallable implements Callable<Long> {

    @Override
    public Long call() throws Exception {
        /*
        //等待3秒
        Thread.sleep(3000);
        return 2;
         */


        Long res = 0L;
        for (Long i = from; i < two; i++) {
            res += i;
        }
        return res;
    }

    /**
     * 开始
     */
    private Long from;
    /**
     * 结束
     */
    private Long two;

    public UseCallable() {
    }

    public UseCallable(Long from, Long two) {
        this.from = from;
        this.two = two;
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {

        /*
        初步理解代码
        //futureTask的用处就是保存一个未来的返回值
        FutureTask<Integer> futureTask=new FutureTask<>(new UseCallable());
        new Thread(futureTask).start();
        //.get()：阻塞的，等待线程的返回值，阻塞主线程（main线程），等待UseCallable执行完，主线程（main线程）才会继续执行下去）
        Integer integer=futureTask.get();
        System.out.println(integer);
         */

        /**
         * 单线程
         */
        //开始时间
        long start = System.currentTimeMillis();
        Long res = 0L;
        for (Long i = 0L; i < 100000000; i++) {
            res += i;
        }
        //结束时间
        long end = System.currentTimeMillis();
        //计算时间
        System.out.println(end - start);
        System.out.println(res);


        /**
         * 多线程
         */
        //开始时间
        start = System.currentTimeMillis();
        res = 0L;

        //用来保存每个线程计算出来的数据
        FutureTask[] futureTasks = new FutureTask[10];

        //启动10个线程
        for (Long i = 0L; i < 10; i++) {
            FutureTask<Long> task = new FutureTask<>(new UseCallable(i * 10000000, (i + 1) * 10000000));
            new Thread(task).start();
            futureTasks[Math.toIntExact(i)] = task;
        }
        for (int i = 0; i < futureTasks.length; i++) {
            Long sum = (Long)futureTasks[i].get();
            res+=sum;
        }
        //结束时间
        end = System.currentTimeMillis();
        //计算时间
        System.out.println(end - start);
        System.out.println(res);

    }
}
